package com.example.fastshareapp;

import java.util.ArrayList;
import java.util.List;

import com.example.fastshareapp.Utilities.BitmapUtil;

import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.provider.SyncStateContract.Constants;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.content.IntentSender.SendIntentException;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.text.Editable;
import android.view.Menu;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.ScrollView;

public class ChatActivity extends Activity implements Observer {

	private static final int HANDLE_APPLICATION_QUIT_EVENT = 0;
	private static final int HANDLE_HISTORY_CHANGED_EVENT = 1;
	private static final int HANDLE_ALLJOYN_ERROR_EVENT = 3;
	private static final int HANDLE_SEND_RECEIVE_IMAGE_ERROR_EVENT = 4;

	private ListView m_listChat;
	private ArrayAdapter<String> m_listChatAdapter;
	private Button m_btnSendMessage;
	private Button m_btnChooseMessage;
	private ImageView m_imgSendImage;
	private boolean m_isSendMessage;
	private final int SENDIMAGE = 10;
	private Uri m_imagePath;
	private MainApp m_mainApp;
	private EditText m_txtMessage;
	private String m_imageName;
	private Bitmap m_imageBitmap;
	private List<Image> listImageSend;
	private ScrollView m_rootScrollView;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_chat);
		m_rootScrollView = (ScrollView)findViewById(R.id.rootScrollView);
		m_listChat = (ListView) findViewById(R.id.listChat);
		m_listChatAdapter = new ArrayAdapter<String>(getApplicationContext(),
				android.R.layout.test_list_item);
		m_listChat.setAdapter(m_listChatAdapter);
		m_btnSendMessage = (Button) findViewById(R.id.btnSendMessage);
		m_btnChooseMessage = (Button) findViewById(R.id.btnChooseImage);
		m_imgSendImage = (ImageView) findViewById(R.id.imgSendImage);
		m_txtMessage = (EditText) findViewById(R.id.txtSendMessage);
		m_isSendMessage = false;
		m_mainApp = (MainApp) getApplication();
		m_mainApp.chechIn();
		m_mainApp.addObserver(this);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.chat, menu);
		return true;
	}

	/*
	 * Define Methods
	 */

	public void didClickSendMessageButton(View v) {
		if (!m_isSendMessage) {
			if (!m_txtMessage.getText().toString().equals("")) {
				m_mainApp.localUserMessage(m_txtMessage.getText().toString());
				m_txtMessage.setText("");
				UpdateListChat();
			}
		} else {
			listImageSend = new ArrayList<Image>();
			listImageSend = BitmapUtil.getListImageToSend(m_imageName,
					Utilities.getImageData(m_imageBitmap));
			m_mainApp.setM_imageInfo(new ImageInfo(listImageSend.get(0).getM_name(), listImageSend.size()));
			m_mainApp.didSendImageInfo();
			m_mainApp.localUserMessage("Sending Image");
			//new AsyncToSendImage(this).execute();
			sendImage();
			deleteImage();
		}
	}

	public Boolean sendImage() {
		for (int i = 0; i < listImageSend.size(); i++) {
			m_mainApp.localUserImage(listImageSend.get(i));
		}
		//m_imageBitmap = null;
		return true;
	}

	public void didClickChooseImageButton(View v) {
		Intent intent = new Intent(Intent.ACTION_PICK,
				android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
		startActivityForResult(intent, SENDIMAGE);
	}

	public void didClickImageSendView(View v) {
		deleteImage();
	}
	
	private void deleteImage(){
		m_isSendMessage = false;
		m_imgSendImage.setImageBitmap(null);
		m_imageName = null;
		m_imageBitmap = null;
	}

	public String getPathFile(Uri imagePath) {
		String pathName;
		String[] proj = { MediaStore.Images.Media.DATA };
		@SuppressWarnings("deprecation")
		Cursor cursor = managedQuery(imagePath, proj, null, null, null);
		int column_index = cursor
				.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
		cursor.moveToFirst();
		pathName = cursor.getString(column_index);
		return pathName;
	}

	private void UpdateListChat() {
		m_listChatAdapter.clear();
		List<String> messages = m_mainApp.getM_listHistory();
		for (String message : messages) {
			m_listChatAdapter.add(message);
		}
		m_listChatAdapter.notifyDataSetChanged();
		ImageInfo _info = m_mainApp.getFirstImageInfo();
		if(_info != null){
			List<Image> images = m_mainApp.getReceivingImageList(_info.getM_name());
			if(images.size() != 0 && images.size() == _info.getM_length()){
				Bitmap receivedImage = BitmapUtil.getBitmapFromList(images, _info.getM_name());
				m_imgSendImage.setImageBitmap(receivedImage);
				m_mainApp.removeCompletedImage(_info.getM_name());
				 m_mainApp.getReceivingImageInfo();
			}
			
		}
		scrollMyListViewToBottom();
	}

	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
		super.onActivityResult(requestCode, resultCode, data);
		switch (requestCode) {

		case SENDIMAGE: {
			if (resultCode == Activity.RESULT_OK) {
				m_isSendMessage = true;
				m_imagePath = data.getData();
				m_imageName = getPathFile(m_imagePath);
				m_imageBitmap = Utilities.getImageLocal(m_imageName, 50);
				m_imgSendImage.setImageBitmap(m_imageBitmap);
			}
			break;
		}
		default:
			break;
		}
	}

	@Override
	public boolean dispatchTouchEvent(MotionEvent ev) {
		// TODO Auto-generated method stub
		  final View currentFocus = getCurrentFocus();
		    if (!(currentFocus instanceof EditText) || !isTouchInsideView(ev, currentFocus)) {
		        ((InputMethodManager) getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE))
		            .hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
		    }
		return super.dispatchTouchEvent(ev);
	}
	private boolean isTouchInsideView(final MotionEvent ev, final View currentFocus) {
	    final int[] loc = new int[2];
	    currentFocus.getLocationOnScreen(loc);
	    return ev.getRawX() > loc[0] && ev.getRawY() > loc[1] && ev.getRawX() < (loc[0] + currentFocus.getWidth())
	        && ev.getRawY() < (loc[1] + currentFocus.getHeight());
	}

	private Handler m_handler = new Handler() {

		@Override
		public void handleMessage(Message msg) {
			switch (msg.what) {
			case HANDLE_APPLICATION_QUIT_EVENT: {
				break;
			}
			case HANDLE_HISTORY_CHANGED_EVENT: {
				UpdateListChat();
				break;
			}
			case HANDLE_ALLJOYN_ERROR_EVENT: {
				break;
			}
			case HANDLE_SEND_RECEIVE_IMAGE_ERROR_EVENT:
			{
				m_mainApp.localUserMessage("Error when Send Or Receive Image");
				break;
			}
			default:
				break;
			}
			super.handleMessage(msg);
		}

	};

	@Override
	public void update(Observable obs, Object obj) {
		String qualifier = (String) obj;

		if (qualifier.equals(MainApp.APPLICATION_QUIT_EVENT)) {
			Message message = m_handler
					.obtainMessage(HANDLE_APPLICATION_QUIT_EVENT);
			m_handler.sendMessage(message);
		}

		if (qualifier.equals(MainApp.HISTORY_CHANGED_EVENT)) {
			Message message = m_handler
					.obtainMessage(HANDLE_HISTORY_CHANGED_EVENT);
			m_handler.sendMessage(message);
		}

		if (qualifier.equals(MainApp.ALLJOYN_ERROR_EVENT)) {
			Message message = m_handler
					.obtainMessage(HANDLE_ALLJOYN_ERROR_EVENT);
			m_handler.sendMessage(message);
		}
		
		if (qualifier.equals(MainApp.SEND_RECEIVE_IMAGE_ERROR_EVENT)) {
			Message message = m_handler
					.obtainMessage(HANDLE_SEND_RECEIVE_IMAGE_ERROR_EVENT);
			m_handler.sendMessage(message);
		}
		
	}
	
	////
	private void scrollMyListViewToBottom() {
	    m_listChat.post(new Runnable() {
	        @Override
	        public void run() {
	            // Select the last row so it will scroll into view...
	        	m_listChat.setSelection(m_listChatAdapter.getCount() - 1);
	        	m_rootScrollView.fullScroll(View.FOCUS_UP);
	        	m_rootScrollView.pageScroll(View.FOCUS_UP);
	        }
	    });
	}
	
}
